package com.weixing.mall.provider.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.enums.OrderAppTagEnum;
import com.weixing.mall.core.enums.OrderSysTagEnum;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.provider.api.erp.entity.SkuInfo;
import com.weixing.mall.provider.api.erp.vo.ResultSkuInfoVo;
import com.weixing.mall.provider.api.model.dto.GoodPrintRpcDto;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.model.vo.*;
import com.weixing.mall.provider.api.model.vo.dto.BillProductDto;
import com.weixing.mall.provider.api.model.vo.dto.BillSaveDto;
import com.weixing.mall.provider.api.model.vo.dto.DepotRPcVo;
import com.weixing.mall.provider.api.service.*;
import com.weixing.mall.provider.mapper.OrderGoodsMapper;
import com.weixing.mall.provider.mapper.OrderMapper;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.domain.OrderGoods;
import com.weixing.mall.provider.model.dto.OrderBoundDto;
import com.weixing.mall.provider.model.dto.SealingSheetDto;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.model.query.OrderPCQuery;
import com.weixing.mall.provider.model.vo.IndexAgencyVo;
import com.weixing.mall.provider.model.vo.OrderGoodsVo;
import com.weixing.mall.provider.model.vo.OrderListPCVo;
import com.weixing.mall.provider.service.IOrderGoodsService;
import com.weixing.mall.provider.service.IOrderPCService;
import com.weixing.mall.provider.service.IOrderService;
import com.weixing.mall.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServicePCImpl implements IOrderPCService {
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private AgencyRpcService agencyRpcService;
    @Autowired
    private LeaveMessageServiceRpc leaveMessageServiceRpc;
    @Autowired
    private DepotServiceRpc depotServiceRpc;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ItemFeign itemFeign;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private SealMathRuleServiceRpc sealMathRuleServiceRpc;
    @Autowired
    private ProductStockServiceRpc productStockServiceRpc;
    @Autowired
    GoodsTransBillServiceRpc goodsTransBillServiceRpc;

    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private ErpFeign erpFeign;

    @Override
    public IPage selectListPC(OrderPCQuery orderPCQuery, Page initMpPage) {
        List<Integer> status = Lists.newArrayList();
        //处理订单状态
        if (ObjectUtil.isNotEmpty(orderPCQuery) && orderPCQuery.getOrderStatus() == null) {
            status.add(OrderStateEnum.AUDIT_SUCCESS.getValue());
            status.add(OrderStateEnum.SEALED.getValue());
            status.add(OrderStateEnum.WAIT_SHIP.getValue());
            orderPCQuery.setStatus(status);
        }
        if (ObjectUtil.isNotEmpty(orderPCQuery) && orderPCQuery.getOrderStatus() != null) {
            status.add(orderPCQuery.getOrderStatus().getValue());
            orderPCQuery.setStatus(status);
        }
        //由于客户这块业务不确定，暂时不对APP仓库和发货部发货的类型进行限制。如果后期限制后参考封单逻辑注释的代码
        if (null == orderPCQuery.getIsProblem()) {
            orderPCQuery.setIsProblem(WhetherEnum.NO);
        }
        if (orderPCQuery.getOrderType() != null && orderPCQuery.getOrderType().getValue().equals(OrderTypeEnum.ALL.getValue())) {
            orderPCQuery.setOrderType(null);
        }
        IPage<OrderListPCVo> orderListPCVoIPage = orderMapper.selectListPC(initMpPage, orderPCQuery, null);
        List<OrderListPCVo> records = orderListPCVoIPage.getRecords();
        //查询审核时间
        List<Long> courseIds = records.stream().map(OrderListPCVo::getId).collect(Collectors.toList());
        if (courseIds.size() == 0) {
            return orderListPCVoIPage;
        }
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().in("order_id", courseIds));
        List<Long> productIds = orderGoodsList.stream().map(OrderGoods::getProductId).collect(Collectors.toList());
        //可以进行优化暂时先用
        long[] productIdsRpc = new long[productIds.size()];
        for (int i = 0; i < productIds.size(); i++) {
            productIdsRpc[i] = productIds.get(i);
        }
        if (productIds.size() == 0) {
            return orderListPCVoIPage;
        }
        List<ActivityProductVo> productVoList = itemFeign.findActProductVoByIds(productIdsRpc).getData();
        //对前端数据进行整合
        for (OrderListPCVo record : records) {
            for (OrderGoods orderGoods : orderGoodsList) {
                if (null != productVoList) {//RPC 调用未返回，内容显示不完全
                    for (ActivityProductVo vo : productVoList) {
                        if (record.getId().equals(orderGoods.getOrderId()) && orderGoods.getProductId().equals(vo.getId())) {
                            record.setGoodsImg(vo.getProductImg());
                            record.setProductSn(vo.getProductSn());
                            record.setProductId(vo.getId());
                            record.setGoodsId(orderGoods.getGoodsId());
                            record.setProductSkuDesp(vo.getProductSkuDesp());
                            record.setStyleNo(orderGoods.getStyleNo());
                        }
                    }
                }
            }
        }
        return orderListPCVoIPage;
    }

    @Override
    public List<OrderListPCVo> selectListPC(OrderPCQuery orderPCQuery) {
        List<Integer> status = Lists.newArrayList();
        //处理订单状态
        if (ObjectUtil.isNotEmpty(orderPCQuery) && orderPCQuery.getOrderStatus() == null) {
            status.add(OrderStateEnum.AUDIT_SUCCESS.getValue());
            status.add(OrderStateEnum.SEALED.getValue());
            status.add(OrderStateEnum.WAIT_SHIP.getValue());
            orderPCQuery.setStatus(status);
        }
        if (ObjectUtil.isNotEmpty(orderPCQuery) && orderPCQuery.getOrderStatus() != null) {
            status.add(orderPCQuery.getOrderStatus().getValue());
            orderPCQuery.setStatus(status);
        }
        //由于客户这块业务不确定，暂时不对APP仓库和发货部发货的类型进行限制。如果后期限制后参考封单逻辑注释的代码
        if (null == orderPCQuery.getIsProblem()) {
            orderPCQuery.setIsProblem(WhetherEnum.NO);
        }
        if (orderPCQuery.getOrderType() != null && orderPCQuery.getOrderType().getValue().equals(OrderTypeEnum.ALL.getValue())) {
            orderPCQuery.setOrderType(null);
        }
        List<OrderListPCVo> records = orderMapper.selectListPC(orderPCQuery, null);
        //查询审核时间
        List<Long> courseIds = records.stream().map(OrderListPCVo::getId).collect(Collectors.toList());
        if (courseIds.size() == 0) {
            return records;
        }
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().in("order_id", courseIds));
        List<Long> productIds = orderGoodsList.stream().map(OrderGoods::getProductId).collect(Collectors.toList());
        //可以进行优化暂时先用
        long[] productIdsRpc = new long[productIds.size()];
        for (int i = 0; i < productIds.size(); i++) {
            productIdsRpc[i] = productIds.get(i);
        }
        if (productIds.size() == 0) {
            return records;
        }
        List<ActivityProductVo> productVoList = itemFeign.findActProductVoByIds(productIdsRpc).getData();
        //对前端数据进行整合
        for (OrderListPCVo record : records) {
            for (OrderGoods orderGoods : orderGoodsList) {
                if (null != productVoList) {//RPC 调用未返回，内容显示不完全
                    for (ActivityProductVo vo : productVoList) {
                        if (record.getId().equals(orderGoods.getOrderId()) && orderGoods.getProductId().equals(vo.getId())) {
                            record.setGoodsImg(vo.getProductImg());
                            record.setProductSn(vo.getProductSn());
                            record.setProductId(vo.getId());
                            record.setGoodsId(orderGoods.getGoodsId());
                            record.setProductSkuDesp(vo.getProductSkuDesp());
                            record.setStyleNo(orderGoods.getStyleNo());
                        }
                    }
                }
            }
        }
        return records;
    }

    /**
     * 封单逻辑---根据精准，先精准-在模糊 ，模糊匹配3个规则进行：
     * 一、如果是精准，则先精准匹配所选择匹配规则里面的仓库，按照顺序进行匹配，如果匹配不到则显示为需外采
     * 二、如果是先精准-在模糊，则先精准匹配所选择匹配规则里面的仓库，按照顺序进行匹配，如果匹配不到，则使用模糊匹配按照所选择匹配规则里面的仓库，按照顺序进行匹配，如果还是匹配不到，则显示需外采。
     * 三、、如果是模糊匹配，则先模糊匹配所选择匹配规则里面的仓库，按照顺序进行匹配，如果匹配不到则显示为需外采。
     *
     * @param sealingSheetDto
     * @param sysAuth
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sealingSheet(SealingSheetDto sealingSheetDto, SysAuth sysAuth) {
        if (ObjectUtil.isEmpty(sealingSheetDto)) {
            throw new BusinessException("参数信息未知");
        }
        if (sealingSheetDto.getOrderIds() == null) {
            throw new BusinessException("未选中订单");
        }
        //需增加判断逻辑为匹配时只有包含APP仓和ERP仓时才进行封单 否则不进行封单操作 2020-5-20
        boolean flag = false;//是否封单操作
        Result<SealMatchRuleVo> result = sealMathRuleServiceRpc.getById(sealingSheetDto.getId());
        /*获取需要匹配的仓库   -----  新规则只匹配APP仓和ERP仓*/
        List<Long> list = Lists.newArrayList();
        if (result.isSuccess() && ObjectUtil.isNotEmpty(result.getData())) {
            SealMatchRuleVo smrv = result.getData();
            if (ObjectUtil.isNotEmpty(smrv.getFirstDepot()) && StrUtil.isNotEmpty(smrv.getFirstDepot().getDepotCode())) {
                loadList(list, smrv.getFirstDepot().getDepotCode(), smrv.getFirstMatch());
            } else if (ObjectUtil.isNotEmpty(smrv.getSecodeDpot()) && StrUtil.isNotEmpty(smrv.getSecodeDpot().getDepotCode())) {
                loadList(list, smrv.getSecodeDpot().getDepotCode(), smrv.getSecondMatch());
            } else if (ObjectUtil.isNotEmpty(smrv.getThridDepot()) && StrUtil.isNotEmpty(smrv.getThridDepot().getDepotCode())) {
                loadList(list, smrv.getThridDepot().getDepotCode(), smrv.getThirdMatch());
            }
            if (list.size() > 0) {
                flag = true;
            }
        }
        if (flag) {
            //查询状态为待封单的订单  或则是模糊匹配的订单
            List<OrderGoods> orderGoodsList = goodsList(sealingSheetDto);
            if (orderGoodsList.size() > 0) {
                //获取用于匹配的商品
                Map<Long, List<ProductStockDetailsVo>> ttMap = getAllMatch(sealingSheetDto.getId(), orderGoodsList, result.getData(), list);
                //执行匹配并返回匹配结果
                Map<Long, BillSaveDto> transMap = accurateAndVague(orderGoodsList, ttMap, sealingSheetDto.getMatchRule(), sealingSheetDto);
                updateOrderStatus(orderGoodsList, sealingSheetDto);
            }
        }
    }

    //*获取需要匹配的仓库
    private List<Long> loadList(List<Long> list, String str, Long id) {
        switch (str) {
            case "APP":
                list.add(id);
                break;
            case "ERP":
                list.add(id);
                break;
            default://2020-6-23 新增默认 无论什么仓库都可以匹配  以前所用的app仓和erp仓匹配逻辑已废除-----都是什么鬼，啥逻辑都一直在变，garbage code
                list.add(id);
                break;
        }
        return list;
    }

    @Override
    public IndexAgencyVo agency(Long uid) {
        int sum = 0;
        IndexAgencyVo vo = new IndexAgencyVo();
        List<Order> orders = orderService.list(new QueryWrapper<Order>().eq("auditor", uid).eq("audit_dept", AuditDeptEnum.SERVICE_DEPT.getValue()));
        vo.setOrder(orders.size());
        sum += orders.size();
        Map<String, Integer> tt = agencyRpcService.selectById(uid);
        if (null != tt) {
            vo.setMedia(tt.get("media"));
            vo.setPublicPool(tt.get("publicPool"));
            sum += tt.get("media");
            sum += tt.get("publicPool");
        }

        Map<String, Integer> noReply = leaveMessageServiceRpc.noReplyList(uid);
        if (null != noReply) {
            vo.setMesage(noReply.get("noReply"));
            sum += noReply.get("noReply");
        }
        vo.setSum(sum);
        return vo;
    }

    /*
     * 生成调拨单
     *
     * */
    @Override
    public void billTrands(SysAuth sysAuth, Long indepotId) {
        //根据需要生成调拨单的订单列表
        List<Order> orderList = getOrderLists(sysAuth);
        //对订单进行过滤，对于该部门负责的仓库以及外采仓进行特殊的处理
        orderList = handerList(orderList, sysAuth);
        //根据仓库Id对值对订单进行分组
        List<Long> depottmpList = orderList.stream().map(Order -> Order.getDepotId()).collect(Collectors.toList());
        //仓库id去重复
        List<Long> depotList = depottmpList.stream().distinct().collect(Collectors.toList());
        //生成调拨单逻辑
        for (Long ll : depotList) {
            List<Order> tmpList = Lists.newArrayList();
            for (Order order : orderList) {
                if (order.getDepotId().equals(ll)) {
                    tmpList.add(order);
                }
            }
            //查询调拨单的商品信息
            List<Long> productList = tmpList.stream().map(Order -> Order.getId()).collect(Collectors.toList());
            //通过订单ID信息查询订单商品，这样做的目的是为了防止order分表导致查询资源的消耗过多。
            List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().in("order_id", productList));
            //对订单进行处理，对于存在重复的商品进行累加
            List<BillProductDto> dtoList = handerBillDtoList(orderGoodsList);
            //对调拨单数据进行整合
            List<DepotRPcVo> tt = depotServiceRpc.getDepotId(ll).getData();
            //二期项目  不在进行数量过滤，一个订单一条记录
           /* for (int i = 0; i < dtoList.size(); i++) {
                BillProductDto dto = dtoList.get(i);
                for (int j = i + 1; j < dtoList.size(); j++) {
                    BillProductDto dto1 = dtoList.get(j);
                    if (dto.getProductId().equals(dto1.getProductId())) {
                        dto.setStock(dto.getStock() + dto1.getStock());
                        dtoList.remove(j);
                        j--;
                    }
                }
            }*/
            //商品调拨数量进行累加
           /* int num = 0;
            for (BillProductDto billProductDto : dtoList) {
                num += billProductDto.getStock();
            }*/
            BillSaveDto billSaveDto = new BillSaveDto();
            billSaveDto.setBillNum(dtoList.size());
            billSaveDto.setInDepotId(indepotId);
            for (DepotRPcVo vos : tt) {
                if (vos.getId().equals(ll)) {
                    billSaveDto.setOutDepotId(vos.getId());
                    billSaveDto.setDepotName(vos.getDepotName());

                }
            }
            billSaveDto.setProductIds(dtoList);
            goodsTransBillServiceRpc.goodstransbill(billSaveDto);
        }
    }

    private List<BillProductDto> handerBillDtoList(List<OrderGoods> orderGoodsList) {
        List<BillProductDto> dtoList = Lists.newArrayList();
        for (OrderGoods orderGoods : orderGoodsList) {
            BillProductDto billProductDto = new BillProductDto();
            billProductDto.setStock(orderGoods.getQuantity());
            billProductDto.setGoodsId(orderGoods.getGoodsId());
            billProductDto.setProductId(orderGoods.getProductId());
            billProductDto.setOrderSn(orderGoods.getOrderSn());
            dtoList.add(billProductDto);
        }
        return dtoList;
    }

    private List<Order> handerList(List<Order> orderList, SysAuth sysAuth) {
        SysUserVo vo = sysUserRpcService.getById(sysAuth.getUid()).getData();
        if (vo.getDeptId() == null) {
            return null;
        }
        List<DepotRPcVo> tt = depotServiceRpc.getDepotId(vo.getDeptId()).getData();
        DepotRPcVo vo2 = depotServiceRpc.getBycode(GlobalConstant.DepotCode.OUT).getData();
        for (DepotRPcVo vo1 : tt) {
            for (int i = 0; i < orderList.size(); i++) {
                Order order = orderList.get(i);
                if (vo1.getId().equals(order.getDepotId()) || vo2.getId().equals(order.getDepotId())) {
                    orderList.remove(i);
                    i--;
                }
            }
        }
        return orderList;
    }

    private List<Order> getOrderLists(SysAuth sysAuth) {
        List<Order> orderList = Lists.newArrayList();
        List<RoleVo> roleVos = sysUserRpcService.getRoleById(sysAuth.getUid()).getData();
        boolean flag = false;
        for (RoleVo vo : roleVos) {
            //如果为发货部主管或者APP仓库主管
            if (vo.getRoleCode().equals(GlobalConstant.RoleCode.APPZG) || vo.getRoleCode().equals(GlobalConstant.RoleCode.FFBZG)) {
                flag = true;

            }
        }
        if (flag) {
            orderList = orderService.list(new QueryWrapper<Order>().eq("order_status", OrderStateEnum.SEALED.getValue()));
        } else {
            orderList = orderService.list(new QueryWrapper<Order>().eq("order_status", OrderStateEnum.SEALED.getValue()).eq("shipper_id", sysAuth.getUid()));
        }
        return orderList;
    }

    private List<OrderGoods> goodsList(SealingSheetDto sealingSheetDto) {
        //TODO 暂时关闭，作用为可以匹配的订单类型，后期如果客户需要在放开，
       /* if (sealingSheetDto.getDept().getValue().equals(SealTypeEnum.SHIPPER.getValue())) {
            tyeps = GlobalConstant.SHIPPER_TYPE;

            sealingSheetDto.setOrderType(OrderTypeEnum.NORMAL);
            sealingSheetDto.setOrderType(OrderTypeEnum.NORMAL);
        } else if (sealingSheetDto.getDept().getValue().equals(SealTypeEnum.APP.getValue())) {
            tyeps = GlobalConstant.APP_TYPE;
        }*/
        if(ObjectUtil.isNull(sealingSheetDto.getOrderType())){
            sealingSheetDto.setOrderType(OrderTypeEnum.ALL);
        }
        List<OrderGoods> orderGoodsList = orderGoodsService.selectByOrderStatus(OrderStateEnum.AUDIT_SUCCESS.getValue(), sealingSheetDto.getOrderType().getValue(), sealingSheetDto.getOrderIds());
        return orderGoodsList;
    }

    private Map<Long, List<ProductStockDetailsVo>> getAllMatch(Long id, List<OrderGoods> orderGoodsList, SealMatchRuleVo vo, List<Long> depotList) {

        /*获取完毕执查询各个仓库中的商品信息*/
        /*TODO 这个地方如果存在ERP则需要和ERP进行匹配和对接*/
        Map<Long, List<ProductStockDetailsVo>> ttMap = new HashMap<Long, List<ProductStockDetailsVo>>();
        for (Long tt : depotList) {
            List<ProductStockDetailsVo> productStockVos = productStockServiceRpc.getAllByDepotId2(tt);
            if (productStockVos != null) {
                ttMap.put(tt, productStockVos);
            }
        }
        //判定ERP仓库逻辑
        boolean erpLoad = erpLoad(vo);
        if (erpLoad) {//和ERP仓库进行匹配，
            // TODO 去erp仓库id，然后封装数据返回
            Result<DepotRPcVo> bycode = depotServiceRpc.getBycode(GlobalConstant.DepotCode.ERP);
            DepotRPcVo data = bycode.getData();
            if (!bycode.isSuccess() || null == data) {
                throw new BusinessException("查询仓库失败");
            }
            List<ProductStockDetailsVo> stockVoList = Lists.newArrayList();
            ProductStockDetailsVo stockVo = null;
            for (OrderGoods orderGoods : orderGoodsList) {
                Result<ResultSkuInfoVo> resultSkuInfoVoResult = erpFeign.selectDepotSkuStockByPage(GlobalConstant.ERP_DEPOT_ID, orderGoods.getStyleNo(), orderGoods.getProductSn());
                if (!resultSkuInfoVoResult.isSuccess()) {
                    continue;
                    //throw new BusinessException("erp调用失败");
                }
                ResultSkuInfoVo skuInfoVo = resultSkuInfoVoResult.getData();
                List<SkuInfo> voData = skuInfoVo.getData();
                //ERP返回空数据这里抛个异常
                if (ObjectUtil.isEmpty(voData)) {
                    continue;
                    //throw new BusinessException("未匹配到ERP数据信息");
                }
                // TODO  商品按款号和sku匹配居然返回List，确定能匹配上？暂时先取列表第一个
                SkuInfo skuInfo = voData.get(0);
                stockVo = new ProductStockDetailsVo();
                stockVo.setStock(Integer.parseInt(skuInfo.getK_num()));
                stockVo.setDepotId(data.getId());
                stockVo.setDepotName(data.getDepotName());
                stockVo.setProductId(orderGoods.getProductId());
                stockVo.setStyleNo(orderGoods.getStyleNo());
                stockVo.setGoodsId(orderGoods.getGoodsId());
                stockVo.setGoodsName(orderGoods.getGoodsName());
                stockVo.setProductSkuDesp(orderGoods.getSkuDesp());
                stockVoList.add(stockVo);
            }
            ttMap.put(data.getId(), stockVoList);
        }
        return ttMap;
    }

    /*
     *
     * 判定匹配规则里面是否存在ERP仓库信息，仓库CODE是不允许修改的。
     * */
    private boolean erpLoad(SealMatchRuleVo vo) {
        String depotCode = GlobalConstant.DepotCode.ERP;//编码不允许修改
        if (null != vo.getFirstDepot() && depotCode.equals(vo.getFirstDepot().getDepotCode())) {
            return true;
        }
        if (null != vo.getSecodeDpot() && depotCode.equals(vo.getSecodeDpot().getDepotCode())) {
            return true;
        }
        if (null != vo.getThridDepot() && depotCode.equals(vo.getThridDepot().getDepotCode())) {
            return true;
        }
        return false;
    }

    private Map<Long, BillSaveDto> accurateAndVague
            (List<OrderGoods> orderGoodsList, Map<Long, List<ProductStockDetailsVo>> ttMap, Integer
                    matchRule, SealingSheetDto sealingSheetDto) {
        Map<Long, BillSaveDto> result = new HashMap<Long, BillSaveDto>();
        if (SealMatchRuleEnum.RULE2.getValue().equals(matchRule)) {// 若选择先精准后模糊则进行两次匹配
            //精准
            orderGoodsList = matchData(orderGoodsList, ttMap, SealMatchRuleEnum.RULE1.getValue(), sealingSheetDto);
            //模糊
            orderGoodsList = matchData(orderGoodsList, ttMap, SealMatchRuleEnum.RULE3.getValue(), sealingSheetDto);
        } else {
            orderGoodsList = matchData(orderGoodsList, ttMap, matchRule, sealingSheetDto);
        }
        //新增逻辑 所有未匹配到商品的订单将直接放入外采仓
        if (orderGoodsList.size() > 0) {
            //查询外采仓信息
            Long depotId = null;
            String depotName = "";
            Result<DepotRPcVo> outVo = depotServiceRpc.getBycode(GlobalConstant.DepotCode.OUT);
            if (outVo.isSuccess() && ObjectUtil.isNotEmpty(outVo.getData())) {
                depotId = outVo.getData().getId();
                depotName = outVo.getData().getDepotName();
            }
            List<Order> list = Lists.newArrayList();
            for (OrderGoods orderGoods : orderGoodsList) {
                Order order = new Order();
                order.setId(orderGoods.getOrderId());
                order.setDepotId(depotId);
                order.setOrderStatus(OrderStateEnum.SEALED.getValue());
                order.setSysTag(OrderSysTagEnum.YFD_TAG_106.getValue());
                order.setAppTag(OrderAppTagEnum.YFD_TAG_104.getValue());
                order.setDepotName(depotName);
                order.setMateRule(sealingSheetDto.getMatchRule().intValue());
                order.setRuleName(matchRuleName(sealingSheetDto.getMatchRule()));
                list.add(order);
            }
            orderService.updateBatchById(list,ListUtil.SIZE);
        }
        return result;
    }

    private List<OrderGoods> matchData(List<OrderGoods> orderGoodsList, Map<Long, List<ProductStockDetailsVo>> ttMap, Integer
            matchRule, SealingSheetDto sealingSheetDto) {
        for (Map.Entry<Long, List<ProductStockDetailsVo>> entry : ttMap.entrySet()) {
            Long depotId = entry.getKey();
            String depotCode = "";
            Result<DepotRPcVo> vo = depotServiceRpc.getById(depotId);
            if (vo.isSuccess() && ObjectUtil.isNotEmpty(vo.getData())) {
                depotCode = vo.getData().getDepotCode();
            }
            List<ProductStockDetailsVo> stockVoList = entry.getValue();
            for (ProductStockDetailsVo stockVo : stockVoList) {
                for (int i = 0; i < orderGoodsList.size(); i++) {
                    OrderGoods orderGoods = orderGoodsList.get(i);
                    Map<String, Long> map = matchRule(matchRule, orderGoods, stockVo, stockVoList);
                    if (map.get("isMatch").intValue() == 1) {//匹配到的商品不在进行二次匹配
                        //System.out.println("匹配到商品，商品信息为：" + depotId + "仓库,商品为" + orderGoods.getGoodsName());
                        orderGoodsList.remove(i);
                        i--;
                        Order order = new Order();
                        order.setId(orderGoods.getOrderId());
                        order.setDepotId(depotId);
                        order.setOrderStatus(OrderStateEnum.SEALED.getValue());
                        order.setSysTag(OrderSysTagEnum.YFD_TAG_106.getValue());
                        order.setAppTag(OrderAppTagEnum.YFD_TAG_104.getValue());
                        order.setDepotName(stockVo.getDepotName());
                        order.setDepotCode(depotCode);
                        order.setStockSn(stockVo.getStockSn());
                        order.setMateRule(map.get("matchRuleVal").intValue());
                        order.setMatchGoodsId(map.get("matchGoodsId"));
                        order.setMatchProductId(map.get("matchProductId"));
                        order.setRuleName(matchRuleName(sealingSheetDto.getMatchRule()));
                        // System.out.println("订单状态修改成功，订单为ID为：" + order.getId());
                        orderMapper.updateById(order);
                        productStockServiceRpc.lockDepot(stockVo.getId());
                    }
                }
            }
        }
        return orderGoodsList;
    }

    private String matchRuleName(Integer val) {
        String name = "";
        if (SealMatchRuleEnum.RULE1.getValue().equals(val)) {
            name = SealMatchRuleEnum.RULE1.getDesp();
        } else if (SealMatchRuleEnum.RULE2.getValue().equals(val)) {
            name = SealMatchRuleEnum.RULE2.getDesp();
        } else if (SealMatchRuleEnum.RULE3.getValue().equals(val)) {
            name = SealMatchRuleEnum.RULE3.getDesp();
        }
        return name;
    }

    private Map<String, Long> matchRule(Integer matchRule, OrderGoods orderGoods, ProductStockDetailsVo stockVo, List<ProductStockDetailsVo> stockVoList) {
        Map<String, Long> map = new HashMap<>();
        //isMatch 代表是匹配到 默认0位匹配到  1 是匹配到的  matchRuleVal是代表的匹配规则val  这里默认是0  匹配到了修改为对应的值
        map.put("isMatch", 0L);
        map.put("matchRuleVal", 0L);
        map.put("matchGoodsId", 0L);
        map.put("matchProductId", 0L);
        //精准匹配问题处理
        if (SealMatchRuleEnum.RULE1.getValue().equals(matchRule) && orderGoods.getProductId().equals(stockVo.getProductId())) {
            //精准匹配
            List<Order> orderjZLists = orderMapper.selectList(new QueryWrapper<Order>()
                    .eq("depot_id", stockVo.getDepotId())
                    .eq("match_product_id", orderGoods.getProductId())
                    .ne("is_created_bill", IsCreatedBillEnum.YES)
                    .and(cq -> cq.eq("order_status", OrderStateEnum.SEALED.getValue()).or().eq("order_status", OrderStateEnum.WAIT_SHIP.getValue())));
            if (orderjZLists.size() >= stockVo.getStock().intValue()) {
                return map;
            }
            map.put("isMatch", 1L);
            map.put("matchRuleVal", SealMatchRuleEnum.RULE1.getValue().longValue());
            map.put("matchGoodsId", stockVo.getGoodsId());
            map.put("matchProductId", stockVo.getProductId());

        } else if (SealMatchRuleEnum.RULE2.getValue().equals(matchRule)) {
            //先请准后模糊匹配规则
            //精准匹配逻辑
            /* if (orderGoods.getProductId().equals(stockVo.getProductId())) {//productId匹配成功 属于精准匹配  val对应精准值
                if(orderjZLists.size()>=stockVo.getStock().intValue()){//精准匹配不成功
                }else{
                    map.put("isMatch", 1L);
                    map.put("matchRuleVal", SealMatchRuleEnum.RULE1.getValue().longValue());
                    map.put("matchGoodsId", stockVo.getGoodsId());
                    map.put("matchProductId", stockVo.getProductId());
                    return  map;
                }
                //模糊匹配逻辑
            } else if (orderGoods.getGoodsId().equals(stockVo.getGoodsId())) {//goodsId匹配成功 属于模糊匹配   val对应模糊值
                Integer  tt=productStockServiceRpc.getByGoodsInfo(stockVo.getDepotId(),stockVo.getGoodsId(),null).getData();
                //检测模糊匹配的库存信息
                if(orderLists.size()>=tt.intValue()){//模糊匹配数据没有锁定，则执行模糊匹配
                    return  map;
                }
                Long  productId=getVagueProductId(stockVoList,orderGoods,stockVo);
                if(productId.longValue()==0L){
                    return map;
                }
                map.put("isMatch", 1L);
                map.put("matchRuleVal", SealMatchRuleEnum.RULE3.getValue().longValue());
                map.put("matchGoodsId", stockVo.getGoodsId());
                //模糊匹配成功后要对模糊匹配进行选择
                map.put("matchProductId", productId);
            }
            //没看明白什么逻辑
           if(map.get("matchRuleVal").longValue()==SealMatchRuleEnum.RULE1.getValue().longValue()){//精准匹配仓库问题
                if(orderLists.size()>=stockVo.getStock().intValue()){
                    map.put("isMatch", 0L);
                    map.put("matchRuleVal", 0L);
                    map.put("matchGoodsId", 0L);
                    map.put("matchProductId", 0L);
                    return map;
                }
            }
            if(map.get("matchRuleVal").longValue()==SealMatchRuleEnum.RULE3.getValue().longValue()) {//模糊匹配仓库问题
                Integer  tt=productStockServiceRpc.getByGoodsInfo(stockVo.getDepotId(),stockVo.getGoodsId(),null).getData();
                if(tt.intValue()<orderLists.size()){
                    map.put("isMatch", 0L);
                    map.put("matchRuleVal", 0L);
                    map.put("matchGoodsId", 0L);
                    map.put("matchProductId", 0L);
                    return map;
                }
            }*/
        } else if (SealMatchRuleEnum.RULE3.getValue().equals(matchRule)) {
            if (orderGoods.getGoodsId().equals(stockVo.getGoodsId())) {
                //模糊匹配
                List<Order> orderLists = orderMapper.selectList(new QueryWrapper<Order>()
                        .eq("depot_id", stockVo.getDepotId())
                        .eq("match_goods_id", orderGoods.getGoodsId())
                        .ne("is_created_bill", IsCreatedBillEnum.YES)
                        .and(cq -> cq.eq("order_status", OrderStateEnum.SEALED.getValue()).or().eq("order_status", OrderStateEnum.WAIT_SHIP.getValue())));
                Integer tt = productStockServiceRpc.getByGoodsInfo(stockVo.getDepotId(), stockVo.getGoodsId(), null).getData();
                if (tt.intValue() <= orderLists.size()) {
                    return map;
                }
                Long productId = getVagueProductId(stockVoList, orderGoods, stockVo);
                if (productId.longValue() == 0L) {
                    return map;
                }
                map.put("isMatch", 1L);
                map.put("matchRuleVal", SealMatchRuleEnum.RULE3.getValue().longValue());
                map.put("matchGoodsId", stockVo.getGoodsId());
                map.put("matchProductId", productId);
            }
        }
        return map;
    }

    private Long getVagueProductId(List<ProductStockDetailsVo> stockVoList, OrderGoods orderGoods, ProductStockDetailsVo stockVo) {
        for (ProductStockDetailsVo productStockVo : stockVoList) {
            if (productStockVo.getGoodsId().equals(orderGoods.getGoodsId())) {
                if (!productStockVo.getProductId().equals(orderGoods.getProductId())) {//如果不相等则判定下该货品是否库存锁定
                    List<Order> orderLists2 = orderMapper.selectList(new QueryWrapper<Order>()
                            .eq("depot_id", stockVo.getDepotId())
                            .eq("match_product_id", productStockVo.getProductId())
                            .ne("is_created_bill", IsCreatedBillEnum.YES)
                            .and(cq -> cq.eq("order_status", OrderStateEnum.SEALED.getValue()).or().eq("order_status", OrderStateEnum.WAIT_SHIP.getValue())));
                    if (orderLists2.size() < productStockVo.getStock().intValue()) {//如果库存小于模糊匹配的数量，则返回
                        return productStockVo.getProductId();
                    }


                }
            }
        }
        return 0L;
    }

    /*
     * 该方放暂时作废，不再使用
     *
     * */
    @Deprecated
    private Map<Long, BillSaveDto> transBillDto(Map<Long, BillSaveDto> transMap) {
     /*   for (Map.Entry<Long, BillSaveDto> entry : transMap.entrySet()) {
            BillSaveDto stockVoList = entry.getValue();
            List<BillProductDto> tt = stockVoList.getBillProductDtoList();
            for (int i = 0; i < tt.size(); i++) {
                BillProductDto dto = tt.get(i);
                dto.setStock(1);//初始化为1
                for (int j = i + 1; j < tt.size(); j++) {
                    BillProductDto dto1 = tt.get(j);
                    if (dto.getProductId().equals(dto1.getProductId())) {
                        dto.setStock(dto.getStock() + 1);
                        tt.remove(j);
                        j--;

                    }
                }
            }

        }*/
        return transMap;
    }
    /*
     *
     *
     *
     * 自动生成调拨单废弃
     * */
/*    private void creatFormByType(Integer dept, Map<Long, BillSaveDto> transMap, Long uid) {
        if (dept.equals(SealTypeEnum.SHIPPER.getValue())) {//发货部调拨单
            creatForm(GlobalConstant.SHIPPER_ID, transMap, uid);
        } else if (dept.equals(SealTypeEnum.APP.getValue())) {//APP仓库调拨单
            creatForm(GlobalConstant.APP_ID, transMap, uid);
        }
    }*/

    private void creatForm(Long inDepotId, Map<Long, BillSaveDto> transMap, Long uid) {
   /*     for (Map.Entry<Long, BillSaveDto> entry : transMap.entrySet()) {
            Long outDepotId = entry.getKey();
            BillSaveDto billSaveDto = entry.getValue();
            billSaveDto.setInDepotId(inDepotId);
            billSaveDto.setOutDepotId(outDepotId);
            billSaveDto.setUid(uid);
            goodsTransBillServiceRpc.goodstransbill(billSaveDto);
            System.out.println("调拨成功：" + billSaveDto.getBillProductDtoList());
        }*/

    }

    /*
     * 没有匹配到的仓库全部修改为外采仓库
     *
     * */
    private void updateOrderStatus(List<OrderGoods> orderGoodsList, SealingSheetDto sealingSheetDto) {
        DepotRPcVo vo = depotServiceRpc.getBycode(GlobalConstant.DepotCode.OUT).getData();
        for (int i = 0; i < orderGoodsList.size(); i++) {
            OrderGoods orderGoods = orderGoodsList.get(i);
            Order order = new Order();
            order.setId(orderGoods.getOrderId());
            order.setDepotName(vo.getDepotName());
            order.setDepotCode(vo.getDepotCode());
            order.setDepotId(vo.getId());
            order.setOrderStatus(OrderStateEnum.SEALED.getValue());
            order.setSysTag(OrderSysTagEnum.YFD_TAG_106.getValue());
            order.setAppTag(OrderAppTagEnum.YFD_TAG_104.getValue());
            order.setMateRule(sealingSheetDto.getMatchRule());
            order.setRuleName(sealingSheetDto.getRuleName());
            orderMapper.updateById(order);
        }
    }

    @Override
    public void batchUpdateGoodsSnPrintVal(Long[] ids) {
        List<Order> list = Lists.newArrayList();
        for (int i = 0; i < ids.length; i++) {
            Order o = new Order();
            o.setId(ids[i]);
            o.setIsGoodsSnPrint(1);
            list.add(o);
        }
        if (list.size() > 0) {
            orderService.updateBatchById(list,ListUtil.SIZE);
        }
    }

    /*
     * 根据查询条件进行订单码的推送
     *
     *
     * */
    @Override
    @Async
    public void selectListPrint(OrderPCQuery orderPCQuery, SysAuth sysAuth) {
        List<Integer> status = Lists.newArrayList();
        //处理订单状态
        if (ObjectUtil.isNotEmpty(orderPCQuery) && orderPCQuery.getOrderStatus() == null) {
            status.add(OrderStateEnum.AUDIT_SUCCESS.getValue());
            status.add(OrderStateEnum.SEALED.getValue());
            status.add(OrderStateEnum.WAIT_SHIP.getValue());
            orderPCQuery.setStatus(status);
        }
        if (ObjectUtil.isNotEmpty(orderPCQuery) && orderPCQuery.getOrderStatus() != null) {
            status.add(orderPCQuery.getOrderStatus().getValue());
            orderPCQuery.setStatus(status);
        }
        //由于客户这块业务不确定，暂时不对APP仓库和发货部发货的类型进行限制。如果后期限制后参考封单逻辑注释的代码
        if (null == orderPCQuery.getIsProblem()) {
            orderPCQuery.setIsProblem(WhetherEnum.NO);
        }
        if (orderPCQuery.getOrderType() != null && orderPCQuery.getOrderType().getValue().equals(OrderTypeEnum.ALL.getValue())) {
            orderPCQuery.setOrderType(null);
        }
        List<GoodPrintRpcDto> orderList = orderMapper.selectPrintList(orderPCQuery);
        for (GoodPrintRpcDto goodPrintRpcDto : orderList) {
            goodPrintRpcDto.setCreatedBy(sysAuth.getUid());
        }
        Result result = itemFeign.printGoods(orderList);

        //进行已经推送的更新操作
        if (result.isSuccess()) {
            for (GoodPrintRpcDto goodPrintRpcDto : orderList) {
                Order order = new Order();
                order.setId(goodPrintRpcDto.getId());
                order.setIsGoodsSnPrint(WhetherEnum.YES.getValue());
                orderMapper.updateById(order);
            }
        }

    }

    /**
     * 二期封单操作逻辑
     *
     * @param sealingSheetDto
     * @param sysAuth
     */
    @Override
    public void sealingSheetLevel2(SealingSheetDto sealingSheetDto, SysAuth sysAuth) {
        if (ObjectUtil.isEmpty(sealingSheetDto)) {
            throw new BusinessException("参数信息未知");
        }
        if (sealingSheetDto.getOrderIds() == null) {
            throw new BusinessException("未选中订单");
        }
        //需增加判断逻辑为匹配时只有包含APP仓和ERP仓时才进行封单 否则不进行封单操作 2020-5-20
        boolean flag = false;//是否封单操作
        List<Long> list = Lists.newArrayList();
        Result<SealMatchRuleVo> result = sealMathRuleServiceRpc.getById(sealingSheetDto.getId());
        if (result.isSuccess() && ObjectUtil.isNotEmpty(result.getData())) {
            SealMatchRuleVo smrv = result.getData();
            if (ObjectUtil.isNotEmpty(smrv.getFirstDepot()) && StrUtil.isNotEmpty(smrv.getFirstDepot().getDepotCode())) {
                loadList(list, smrv.getFirstDepot().getDepotCode(), smrv.getFirstMatch());
            } else if (ObjectUtil.isNotEmpty(smrv.getSecodeDpot()) && StrUtil.isNotEmpty(smrv.getSecodeDpot().getDepotCode())) {
                loadList(list, smrv.getSecodeDpot().getDepotCode(), smrv.getSecondMatch());
            } else if (ObjectUtil.isNotEmpty(smrv.getThridDepot()) && StrUtil.isNotEmpty(smrv.getThridDepot().getDepotCode())) {
                loadList(list, smrv.getThridDepot().getDepotCode(), smrv.getThirdMatch());
            }
            if (list.size() > 0) {
                flag = true;
            }
        }
        if (flag) {
            //查询状态为待封单的订单  或则是模糊匹配的订单
            List<OrderGoods> orderGoodsList = goodsList(sealingSheetDto);
            if (orderGoodsList.size() > 0) {
                //获取用于匹配的商品
                Map<Long, List<ProductStockDetailsVo>> ttMap = getAllMatch2(sealingSheetDto.getId(), orderGoodsList, result.getData(), list);
                //执行匹配并返回匹配结果
                Map<Long, BillSaveDto> transMap = accurateAndVague2(orderGoodsList, ttMap, sealingSheetDto.getMatchRule(), sealingSheetDto);
                updateOrderStatus(orderGoodsList, sealingSheetDto);
            }
        }
    }

    /**
     * 检查订单解绑是否符合要求
     *
     * @param ids 检查解绑订单的订单id
     * @return 返回结构，为空代表通过，不为空则返回订单编码
     */
    @Override
    public String orderCheckUnbound(List<Long> ids) {
        List<Order> orderList = orderService.list(new QueryWrapper<Order>().in("id", ids));
        List<Integer> checkStatus = Lists.newArrayList();
        checkStatus.add(OrderSysTagEnum.DFH_TAG_108.getValue());
        checkStatus.add(OrderSysTagEnum.YFD_TAG_106.getValue());
        checkStatus.add(OrderSysTagEnum.DD_TAG_301.getValue());
        checkStatus.add(OrderSysTagEnum.DH_TAG_302.getValue());
        checkStatus.add(OrderSysTagEnum.YXH_TAG_303.getValue());
        checkStatus.add(OrderSysTagEnum.YXH1_TAG_304.getValue());
        checkStatus.add(OrderSysTagEnum.ZHH_TAG_305.getValue());
        for (Order order : orderList) {
            int falg = 0;
            if (order.getStockSn() == null) {
                return "存在未绑定订单，无法操作,订单编号为：" + order.getOrderSn();
            }
            if (order.getSysTag().intValue() == OrderSysTagEnum.YFH_TAG_109.getValue().intValue() || order.getSysTag().intValue() == OrderSysTagEnum.YWC_TAG_110.getValue().intValue()) {
                return "存在已发货订单，无法操作订单编号为：" + order.getOrderSn();
            }
            for (Integer tt : checkStatus) {
                if (tt.intValue() == order.getSysTag().intValue()) {
                    falg = 1;
                    break;
                }
            }
            if (falg == 0) {
                return "订单编号为：" + order.getOrderSn() + "订单状态无法进行解绑或绑定，请查看！";
            }
        }
        return null;
    }

    /**
     * 批量解绑订单和库存编码的绑定关系
     *
     * @param ids 订单ID集合
     */
    @Override
    public void orderUnbound(List<Long> ids) {
        orderMapper.orderUnbound(ids);
    }

    /**
     * 获取首页当前订单的内容信息
     *
     * @return
     */
    @Override
    public Map<String, Object> loadAdminIndex() {
        Map<String, Object> result = new HashMap<>();
        /*今日订单总数*/
        Integer total = orderMapper.loadAdminIndex(null);
        /*已发货数量*/
        Integer send = orderMapper.loadAdminIndex(ProductStatusEnum.STATUS3.getValue().toString());
        /*今日已取消数量*/
        Integer canel = orderMapper.loadAdminIndex(ProductStatusEnum.STATUS7.getValue().toString());
        /*今日已取消数量*/
        Integer dh = orderMapper.loadAdminIndex(ProductStatusEnum.STATUS6.getValue().toString());
        result.put("total", total);
        result.put("send", send);
        result.put("canel", canel);
        result.put("dh", dh);
        return result;
    }

    /**
     * 检查订单煮状态是否满足重置要求
     *
     * @param id 订单id
     * @return
     */
    @Override
    public String checkOrderStatus(Long id) {
        Order order = orderService.getById(id);
        //只有断货和取消可以重置，其他状态不允许重置
        if (ProductStatusEnum.STATUS6.getValue().equals(order.getItemStatus()) || ProductStatusEnum.STATUS7.getValue().equals(order.getItemStatus())) {
        } else {
            return "存在不是断货和取消状态的订单，不允许重置";

        }
        return null;
    }

    /**
     * 重置取消和断货状态为空
     *
     * @param id
     */
    @Override
    public void orderResetStatus(Long id) {
        orderMapper.orderResetStatus(id);
    }

    /**
     * 库存编码的重新绑定
     *
     * @param orderBoundDto
     */
    @Override
    public void OrderBoundDto(OrderBoundDto orderBoundDto) {
        Order order = orderService.getById(orderBoundDto.getOrderId());
        if (order.getStockSn() != null&&order.getStockSn().trim().equals("")){
            throw new RuntimeException("库存编码不为空，不允许重新绑定");
        }
        orderMapper.OrderBound(orderBoundDto);
        //锁定库存
        Result result = productStockServiceRpc.lockDepot(orderBoundDto.getProductStockId());
       /* if (!result.isSuccess()) {
            throw new RuntimeException("库存编码锁定失败！");
        }*/
    }

    /**
     * 订单无图片同步接口
     */
    @Override
    public void orderSyn() {
        List<OrderGoodsVo> orderGoodsVoList = orderGoodsMapper.orderSyn();
        for (OrderGoodsVo vo : orderGoodsVoList) {
            if (ObjectUtil.isNotEmpty(vo.getProductImg())) {
                OrderGoods orderGoods = new OrderGoods();
                orderGoods.setId(vo.getId());
                orderGoods.setGoodsImg(vo.getProductImg());
                orderGoodsService.updateById(orderGoods);

            }
        }

    }

    /**
     * 执行封单操作
     *
     * @param orderGoodsList
     * @param ttMap
     * @param matchRule
     * @param sealingSheetDto
     * @return
     */
    private Map<Long, BillSaveDto> accurateAndVague2(List<OrderGoods> orderGoodsList, Map<Long, List<ProductStockDetailsVo>> ttMap, Integer matchRule, SealingSheetDto sealingSheetDto) {
        Map<Long, BillSaveDto> result = new HashMap<Long, BillSaveDto>();
        if (SealMatchRuleEnum.RULE2.getValue().equals(matchRule)) {// 若选择先精准后模糊则进行两次匹配
            //精准
            orderGoodsList = matchData2(orderGoodsList, ttMap, SealMatchRuleEnum.RULE1.getValue(), sealingSheetDto);
            //模糊
            orderGoodsList = matchData2(orderGoodsList, ttMap, SealMatchRuleEnum.RULE3.getValue(), sealingSheetDto);
        } else {
            orderGoodsList = matchData2(orderGoodsList, ttMap, matchRule, sealingSheetDto);
        }
        //新增逻辑 所有未匹配到商品的订单将直接放入外采仓
        if (orderGoodsList.size() > 0) {
            //查询外采仓信息
            Long depotId = null;
            String depotName = "";
            Result<DepotRPcVo> outVo = depotServiceRpc.getBycode(GlobalConstant.DepotCode.OUT);
            if (outVo.isSuccess() && ObjectUtil.isNotEmpty(outVo.getData())) {
                depotId = outVo.getData().getId();
                depotName = outVo.getData().getDepotName();
            }
            List<Order> list = Lists.newArrayList();
            for (OrderGoods orderGoods : orderGoodsList) {
                Order order = new Order();
                order.setId(orderGoods.getOrderId());
                order.setDepotId(depotId);
                order.setOrderStatus(OrderStateEnum.SEALED.getValue());
                order.setSysTag(OrderSysTagEnum.YFD_TAG_106.getValue());
                order.setAppTag(OrderAppTagEnum.YFD_TAG_104.getValue());
                order.setDepotName(depotName);
                order.setMateRule(sealingSheetDto.getMatchRule().intValue());
                order.setRuleName(matchRuleName(sealingSheetDto.getMatchRule()));
                list.add(order);
            }
            orderService.updateBatchById(list, ListUtil.SIZE);
        }
        return result;

    }

    private List<OrderGoods> matchData2(List<OrderGoods> orderGoodsList, Map<Long, List<ProductStockDetailsVo>> ttMap, Integer matchRule, SealingSheetDto sealingSheetDto) {
        for (Map.Entry<Long, List<ProductStockDetailsVo>> entry : ttMap.entrySet()) {
            Long depotId = entry.getKey();
            String depotCode = "";
            Result<DepotRPcVo> vo = depotServiceRpc.getById(depotId);
            if (vo.isSuccess() && ObjectUtil.isNotEmpty(vo.getData())) {
                depotCode = vo.getData().getDepotCode();
            }
            List<ProductStockDetailsVo> stockVoList = entry.getValue();

            for (int i = 0; i < orderGoodsList.size(); i++) {
                OrderGoods orderGoods = orderGoodsList.get(i);
                Map<String, Object> map = matchRule2(matchRule, orderGoods, stockVoList);
                if (Long.valueOf(map.get("isMatch").toString()).longValue()==1L) {//匹配到的商品不在进行二次匹配
                    //System.out.println("匹配到商品，商品信息为：" + depotId + "仓库,商品为" + orderGoods.getGoodsName());
                    orderGoodsList.remove(i);
                    i--;
                    Order order = new Order();
                    order.setId(orderGoods.getOrderId());
                    order.setDepotId(depotId);
                    order.setOrderStatus(OrderStateEnum.SEALED.getValue());
                    order.setSysTag(OrderSysTagEnum.YFD_TAG_106.getValue());
                    order.setAppTag(OrderAppTagEnum.YFD_TAG_104.getValue());
                    order.setDepotName(map.get("depotName").toString());
                    order.setDepotCode(depotCode);
                    order.setMateRule(Integer.valueOf(map.get("matchRuleVal").toString()));
                    order.setMatchGoodsId(Long.valueOf(map.get("matchGoodsId").toString()));
                    order.setMatchProductId(Long.valueOf(map.get("matchProductId").toString()));
                    order.setRuleName(matchRuleName(sealingSheetDto.getMatchRule()));
                    order.setStockSn(map.get("stockSn").toString());
                    order.setStockId(Long.valueOf(map.get("stockId").toString()));
                    // System.out.println("订单状态修改成功，订单为ID为：" + order.getId());
                    orderMapper.updateById(order);
                }
            }

        }
        return orderGoodsList;

    }

    /**
     * 项目二期执行封单操作
     *
     * @param matchRule
     * @param orderGoods
     * @param stockVoList
     * @return
     */
    private Map<String, Object> matchRule2(Integer matchRule, OrderGoods orderGoods, List<ProductStockDetailsVo> stockVoList) {
        Map<String, Object> map = new HashMap<>();
        //isMatch 代表是匹配到 默认0位匹配到  1 是匹配到的  matchRuleVal是代表的匹配规则val  这里默认是0  匹配到了修改为对应的值
        map.put("isMatch", 0L);
        map.put("matchRuleVal", 0L);
        map.put("matchGoodsId", 0L);
        map.put("matchProductId", 0L);
        map.put("stockId", 0L);
        if (SealMatchRuleEnum.RULE1.getValue().equals(matchRule)) {//精准匹配
            for (int i = 0; i < stockVoList.size(); i++) {
                ProductStockDetailsVo productStockDetailsVo = stockVoList.get(i);
                if (productStockDetailsVo.getProductId().equals(orderGoods.getProductId())) {
                    stockVoList.remove(i);
                    i--;
                    map.put("isMatch", 1L);
                    map.put("matchRuleVal", matchRule.longValue());
                    map.put("matchGoodsId", productStockDetailsVo.getGoodsId());
                    map.put("matchProductId", productStockDetailsVo.getProductId());
                    map.put("stockId", productStockDetailsVo.getId());
                    map.put("depotName", productStockDetailsVo.getDepotName());
                    map.put("stockSn", productStockDetailsVo.getStockSn());
                    productStockServiceRpc.lockDepot(productStockDetailsVo.getId());
                    return map;
                }
            }
        } else if (SealMatchRuleEnum.RULE3.getValue().equals(matchRule)) {//模糊匹配
            for (int i = 0; i < stockVoList.size(); i++) {
                ProductStockDetailsVo productStockDetailsVo = stockVoList.get(i);
                if (productStockDetailsVo.getGoodsId().equals(orderGoods.getGoodsId())) {
                    stockVoList.remove(i);
                    i--;
                    map.put("isMatch", 1L);
                    map.put("matchRuleVal", matchRule.longValue());
                    map.put("matchGoodsId", productStockDetailsVo.getGoodsId());
                    map.put("matchProductId", productStockDetailsVo.getProductId());
                    map.put("stockId", productStockDetailsVo.getId());
                    map.put("depotName", productStockDetailsVo.getDepotName());
                    map.put("stockSn", productStockDetailsVo.getStockSn());
                    productStockServiceRpc.lockDepot(productStockDetailsVo.getId());
                    return map;
                }
            }
        }
        return map;
    }

    /**
     * 二期不在远程查询ERP仓库，在本地进行结果查询。
     *
     * @param id
     * @param orderGoodsList
     * @param data
     * @param list
     * @return
     */
    private Map<Long, List<ProductStockDetailsVo>> getAllMatch2(Long id, List<OrderGoods> orderGoodsList, SealMatchRuleVo data, List<Long> list) {
        //二期不在和ERP实时同步了，查询本地数据库
        Map<Long, List<ProductStockDetailsVo>> ttMap = new HashMap<Long, List<ProductStockDetailsVo>>();
        for (Long tt : list) {
            List<ProductStockDetailsVo> productStockVos = orderMapper.getAllByDepotId(tt);
           /* List<ProductStockDetailsVo> productStockVos = productStockServiceRpc.getAllByDepotId2(tt);*/
            if (productStockVos != null) {
                ttMap.put(tt, productStockVos);
            }
        }
        return ttMap;
    }

}
